package com.jianhong.li.extend;

import com.jianhong.li.test.ObjectDiffTest.Bar;
import com.tujia.framework.diff.danielbechler.diff.ObjectDiffer;
import com.tujia.framework.diff.danielbechler.diff.ObjectDifferBuilder;
import com.tujia.framework.diff.danielbechler.diff.identity.IdentityStrategy;
import com.tujia.framework.diff.danielbechler.diff.node.DiffNode;
import com.tujia.framework.diff.render.DiffPathBuilder;
import com.tujia.framework.diff.render.DiffPathFormatter;
import com.tujia.framework.diff.visitor.TnsVisitor;
import com.tujia.framework.diff.visitor.bean.DiffPath;
import org.apache.commons.lang.ObjectUtils;


/**
 * @author jianhong.li Date: 2019-10-16 Time: 3:19 PM
 * @version $Id$
 */
public class SimpleDiff {
    public static String diff(Object base, Object working, DiffPathFormatter diffPathFormatter) {
        try {
            // start of java-object-diff module
            ObjectDiffer objectDiffer =
                ObjectDifferBuilder.startBuilding()
                                   .identity()
                                   .setDefaultCollectionItemIdentityStrategy(new IdentityStrategy() {
                                       @Override
                                       public boolean equals(Object working, Object base) {
                                           if (working == base) {
                                               return true;
                                           }
                                           if (working instanceof Bar && base instanceof Bar) {
                                               System.out.println(
                                                   "自定义相等比较*****************,working:" + working + ",base: " + base);
                                               return ((Bar) working).getId().equals(((Bar) base).getId());
                                           }
                                           return ObjectUtils.equals(working,base);
                                       }
                                   }).and().build();
            final DiffNode root = objectDiffer.compare(working, base);
            final TnsVisitor visitor = new TnsVisitor(working, base);
            root.visit(visitor);
            // end of java-object-diff module

            DiffPath diffPath = new DiffPathBuilder(visitor).createDiffPath();
            if (diffPath == null) {
                return "";
            }
            return diffPathFormatter.format(diffPath);
        } catch (Exception e) {

            return "";
        }
    }

}
